import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 利用阻塞队列来控制线程之间的通信
 *
 */
public class BlockingQueueThreadCommunication {

	public static void main(String[] args) {
		
		final Businiss businiss = new Businiss();
		
		new Thread(new Runnable(){
			public void run() {
				for(int i=0;i<10;i++){
					businiss.sub(i);
				}
			}
		}).start();
		
		for(int i=0;i<10;i++){
			businiss.main(i);
		}
		
	}
	
	static class Businiss {
		
		private BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
		private BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
		
		{
			//HashMap 不是线程安全的多线程的时候会有线程安全问题,影响性能,可能会有以下做法
//			Collections.synchronizedMap(null); 
			try {
				queue2.put(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public void main(int loop){
			try {
				queue1.put(1);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			for(int i=0;i<10;i++) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("main task " + i + " of loop " + loop);
			}
			try {
				queue2.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public void sub(int loop){
			try {
				queue2.put(1);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			for(int i=0;i<10;i++) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("sub task " + i + " of loop " + loop);
			}
			try {
				queue1.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

}
